//-----------------------------------------------------------------------

// <copyright file="RegExTextFieldDefinition.cs" company="Jamie Knight">

// Copyright (c) Jamie Knight. All rights reserved.

// </copyright>

//-----------------------------------------------------------------------

using System;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Windows.Data;

namespace DevKnightlie.WPF.AutoForm.FieldDefinitions
{

    public class RegexMatchValidationRule : ValidationRule
    {
        #region Private Fields

        private String _regExPattern;
        private Regex _regex;

        #endregion

        #region Properties

        public String RegExPattern
        {
            get { return _regExPattern; }
            set
            {
                _regExPattern = value;
                _regex = new Regex(value);
            }
        }

        #endregion


        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            bool isValid = false;
            isValid = _regex.IsMatch(value as String);
            return new ValidationResult(isValid, null);
        }

        public RegexMatchValidationRule(String regExPattern)
        {
            _regex = new Regex(regExPattern);
        }
    }


    /// <summary>
    /// Field definition class which builds a TextBox control. A KeyPreview event handler ensures key presses match a RegEx pattern
    /// </summary>
    public class RegexTextFieldDefinition : BaseFieldDefinition
    {
        #region Private Fields

        private String _regexPattern;
        RegexMatchValidationRule _validation;

        #endregion


        #region Properties

        /// <summary>
        /// Sets or returns the RegEx pattern used to validate text
        /// </summary>
        public String RegexPattern
        {
            get { return _regexPattern; }
            set { _regexPattern = value; }
        }

        #endregion


        #region Methods

        public override void BuildInputControl()
        {
            TextBox textBox = new TextBox()
            {
                TextAlignment = System.Windows.TextAlignment.Right,
                VerticalContentAlignment = System.Windows.VerticalAlignment.Center
            };
            Binding textBinding = new Binding(PropertyName);
            _validation = new RegexMatchValidationRule(RegexPattern);
            textBinding.ValidationRules.Add(_validation);
            BindingOperations.SetBinding(textBox, TextBox.TextProperty, textBinding);
            SetupEnabledBinding(textBox);
            ContainerControl = InputControl = textBox;
        }


        #endregion

    }
}
